package org.example.trainTicketSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.trainTicketSystem.DTO.GetTicketDTO;
import org.example.trainTicketSystem.entity.Ticket;
import org.example.trainTicketSystem.service.TicketService;
import org.example.trainTicketSystem.utils.ResponseResult;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/tickets")
@RequiredArgsConstructor
public class TicketController {

    private final TicketService ticketService;

    @GetMapping()
    public ResponseResult<Page<Ticket>> getTicket(
            @Valid @ParameterObject @ModelAttribute GetTicketDTO getTicketDTO,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        // 规范化分页参数
        page = Math.max(1, page);
        size = Math.min(Math.max(1, size), 100);

        try {
            Page<Ticket> tickets = ticketService.getTicketsBy(getTicketDTO, page, size);

            // 记录日志，但不包含敏感信息
            log.info("Ticket search performed: page={}, size={}, total={}",
                    page, size, tickets.getTotal());

            // 检查是否有结果
            if (tickets.getRecords().isEmpty()) {
                log.info("No tickets found for the given search criteria");
                return ResponseResult.success("未找到符合条件的车票", tickets);
            }

            return ResponseResult.success("车票信息获取成功", tickets);
        } catch (Exception e) {
            // 记录异常，但不暴露敏感错误细节
            log.error("Error retrieving tickets", e);
            return ResponseResult.fail("车票信息获取失败");
        }
    }
}